package org.anderground.app.view.dialogs;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import org.anderground.app.R;
import org.anderground.core.model.Station;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * StationsDialog class.
 * 
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 */
public class StationsDialog extends ItemsDialog<Station> {

	/**
	 * public constructor
	 * 
	 * @param context
	 */
	public StationsDialog(Context context) {
		super(context);
		// TODO
		// setTitle("Multiple stations");
		// setIcon(null);

	}

	/**
	 * show the dialog if it has not already shown
	 * 
	 * @param stationsList
	 */
	public void show(List<Station> stationsList) {
		Station[] stations = stationsList.toArray(new Station[stationsList
				.size()]);
		this.show(stations);
	}

	@Override
	public void show(Station[] stations) {
		Arrays.sort(stations, new Comparator<Station>() {
			public int compare(Station object1, Station object2) {
				return object1.getName().compareToIgnoreCase(object2.getName());
			}
		});

		final ItemView[] stationItemViews = new ItemView[stations.length];
		for (int i = 0; i < stations.length; i++) {
			stationItemViews[i] = new ItemView(getContext());
			stationItemViews[i].setStation(stations[i]);
		}
		ArrayAdapter<Station> arrayAdapter = new ArrayAdapter<Station>(
				getContext(), R.layout.station_row, R.id.station_name, stations) {

			public View getView(int position, View convertView, ViewGroup parent) {
				return stationItemViews[position];
			}

		};
		super.show(stations, arrayAdapter);
	}

	/**
	 * ItemView class.
	 * 
	 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
	 */
	public class ItemView extends LinearLayout {

		/** station to draw */
		private Station station;

		/** icon in the row */
		private StationIcon stationIcon;

		/** textView containing station name */
		private TextView stationName;

		/**
		 * @param context
		 */
		public ItemView(Context context) {
			super(context);
			init();
		}

		/**
		 * linking to layout views
		 */
		private void init() {
			LayoutInflater.from(getContext()).inflate(R.layout.station_row,
					this, true);

			this.stationIcon = (StationIcon) findViewById(R.id.station_icon);
			this.stationName = (TextView) findViewById(R.id.station_name);
		}

		/**
		 * @return the station
		 */
		public Station getStation() {
			return station;
		}

		/**
		 * @param station
		 *            the station to set
		 */
		public void setStation(Station station) {
			this.station = station;
			this.stationIcon.setStation(station);
			this.stationName.setText(station.getName());
		}

	}

}
